In [5]:
"""
This script compares three variants of the "primes" code:

    (1) pure python
    (2) cython
    (3) pure c (no python import)

"""

from cython_test import primes_py, primes
#import primes_py #  the pure python variant
#import primes # the cython variant
import os # to run the C-
import sys
import time

print "\n"
print "=" * 70
print "   B E N C H M A R K     Python - Cython - C"
print "=" * 70
print "\n" * 2

t0 = time.time()
print "starting with the cython module ..."
r1 = primes.primes(10000)
t1 = time.time()
print "done in", t1 - t0, "seconds\n"

t2 = time.time()
print "executing C file via system command ..."
os.system('./primes_c')
t3 = time.time()
print "done in", t3 - t2, "seconds\n"

t4 = time.time()
print "running pure python code ... (this may take a while)"
sys.stdout.write(' ')
sys.stdout.flush()
primes_py.primes(10000)
t5 = time.time()
print "done in", t5 - t4, "seconds\n"

print "\n", "=" * 70, "\n" * 2



======================================================================
   B E N C H M A R K     Python - Cython - C
======================================================================



starting with the cython module ...
done in 0.242857933044 seconds

executing C file via system command ...
done in 0.603439092636 seconds

running pure python code ... (this may take a while)
 done in 82.1965498924 seconds


====================================================================== 


This is the content of primes.py


In [ ]:
import numpy as np
def primes(kmax):
    result = []
    p = np.zeros(10000)
    if kmax > 10000:
        kmax = 10000
    k = 0
    n = 2
    while k < kmax:
        i = 0
        while i < k and n % p[i] != 0:
            i = i + 1
        if i == k:
            p[k] = n
            k = k + 1
            result.append(n)
        n = n + 1
    return result

This is the content of primes.pyx


In [ ]:
def primes(int kmax):
    cdef int n, k, i
    cdef int p[10000]
    result = []
    if kmax > 10000:
        kmax = 10000
    k = 0
    n = 2
    while k < kmax:
        i = 0
        while i < k and n % p[i] != 0:
            i = i + 1
        if i == k:
            p[k] = n
            k = k + 1
            result.append(n)
        n = n + 1
    return result